<template>
  <div>
    <div class="search">
      <input v-model="keyWords" class="search_input" type="text" placeholder="输入城市名或拼音">
    </div>
    <div class="search_content" ref="search" v-show="keyWords">
      <ul class="list">
        <li class="item border-bottom" @click="handleCityClick(item.name)" v-for="(item, index) of searchList" :key="index">{{item.name}}</li>
        <li class="item border-bottom" v-show="hasNoData">没有找到匹配的数据</li>
      </ul>
    </div>
  </div>
</template>

<script>
import Bscroll from 'better-scroll'
export default {
  name: 'citySearch',
  props: {
    cities: Object
  },
  data () {
    return {
      keyWords: '',
      searchList: [],
      timer: null
    }
  },
  methods: {
    handleCityClick (city) {
      this.$store.commit('changeCity', city)
      this.$router.push('/')
    }
  },
  computed: {
    hasNoData () {
      return !this.searchList.length
    }
  },
  watch: {
    keyWords () {
      if (this.timer) {
        clearTimeout(this.time)
      }
      if (!this.keyWords) {
        this.searchList = []
        return
      }
      this.timer = setTimeout(() => {
        let result = []
        for (let i in this.cities) {
          this.cities[i].forEach(value => {
            if (value.spell.indexOf(this.keyWords) > -1 || value.name.indexOf(this.keyWords) > -1) {
              result.push(value)
            }
          })
          this.searchList = result
        }
      })
    }
  },
  mounted () {
    this.scroll = new Bscroll(this.$refs.search)
  }
}
</script>
<style lang="stylus" scoped>
@import '~styles/varibles.styl'
.search
  height .72rem
  padding 0 .1rem
  background $bgColor
  .search_input
    box-sizing border-box
    width 100%
    height .62rem
    line-height .62rem
    border-radius .06rem
    text-align center
    color #666
    padding 0 .1rem
.search_content
  z-index 1
  position absolute
  left 0
  right 0
  bottom 0
  top 1.58rem
  background #eee
  .list
    .item
      line-height .62rem
      color #666
      padding-left .2rem
      background #fff
</style>
